package com.cjkj.equipment.config.sharding;

import com.cjkj.common.core.utils.DateUtils;
import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.*;

/**
 * ShardingSphere自定义分库算法
 * @author cjkj
 * @date 2024-08-30
 */
@Slf4j
public class TJ03DataBaseShardingAlgorithm implements StandardShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
//        log.info("[精准分库算法]");
        // 根据当前时间戳来分库
        Long mills = preciseShardingValue.getValue();
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date(mills));
        for (String each : collection) {
            if (each.endsWith(year)) {
//                log.info("[精准分库算法-数据库]："+ each);
                return each;
            }
        }

        throw new IllegalArgumentException();
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
//        log.info("[范围分库算法]");
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        Date start = new Date(valueRange.lowerEndpoint());
        Date end = new Date(valueRange.upperEndpoint());

        Set<String> result = new HashSet<>();
        List<Date> datesInTheDateRange = DateUtils.getAllDatesInTheDateRange(start, end);
        for (String availableTargetName : collection) {
            for (Date date: datesInTheDateRange){
                String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY, date);
                if (availableTargetName.endsWith(dateStr)) {
                    result.add(availableTargetName);
                }
            }
        }
//        log.info("范围分库算法result"+ JSONObject.toJSONString(result));
        return result;
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
